<template>
  <div class="elder-list-container">
    <div class="fixed-header">
      <div class="page-header">
        <h3>老人管理</h3>
        <div class="search-group">
          <!-- 姓名搜索 -->
          <el-input
              v-model="searchParams.elderName"
              placeholder="请输入姓名"
              clearable
              style="width: 200px"
          />

          <!-- 电话搜索 -->
          <el-input
              v-model="searchParams.phone"
              placeholder="请输入电话"
              clearable
              style="width: 200px"
          />

          <el-select
              v-model="searchParams.communityId"
              placeholder="选择社区"
              filterable
              remote
              :remote-method="filterCommunity"
              :loading="communityLoading"
              clearable
              style="width: 200px"
          >
            <el-option
                v-for="item in filteredCommunityList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>

          <!-- 搜索按钮 -->
          <el-button type="primary" @click="handleSearch">搜索</el-button>

          <!-- 重置按钮 -->
          <el-button @click="resetSearch">重置</el-button>
        </div>
        <el-button type="primary" :icon="Plus" @click="handleAdd">添加老人</el-button>
      </div>
    </div>

    <el-table
        :data="elderList"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
        row-class-name="table-row"
    >
      <el-table-column prop="avatar" label="头像" width="100" align="center">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar">
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt=""/>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="elderName" label="姓名" align="center" min-width="120"/>
      <el-table-column prop="phone" label="手机号" align="center" min-width="150"/>
      <el-table-column label="所属社区" align="center" min-width="150">
        <template #default="{ row }">
          {{ row.communityId === 0 ? '无' : row.communityName }}
        </template>
      </el-table-column>
      <el-table-column label="健康状态" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="getHealthStatusType(row)">{{ getHealthStatusText(row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="500" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="success" :icon="View" @click="handleViewHealth(row)">健康信息</el-button>
          <el-button type="info" :icon="List" @click="handleCheckTasks(row)">检查任务</el-button>
          <el-button type="danger" :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑老人对话框 -->
    <elder-form-dialog
        v-model="elderFormVisible"
        :is-edit="dialogType === 'edit'"
        :elder="currentElder"
        :community-list="communityList"
        @success="handleSuccess"
    />

    <!-- 健康信息对话框 -->
    <health-info-dialog
        v-model="healthDialog"
        :elder="currentElder"
        @success="handleSuccess"
    />

    <!-- 检查任务对话框 -->
    <check-task-dialog
        v-model="taskDialog"
        :elder="currentElder"
        @success="handleSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, onActivated} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus, Edit, View, Delete, List} from '@element-plus/icons-vue'
import type {Elder} from '@/types/elder'
import {getAllElders, deleteElder} from '@/api/elder'
import {getAllCheckTypes} from '@/api/checkType'
import {getAllCommunities} from '@/api/community'
import type {Community} from '@/types/community'
import {getAllDoctors} from '@/api/doctor'
import type {Doctor} from '@/types/doctor'
import {getElderCheckTasks} from '@/api/checkTask'
import ElderFormDialog from './components/ElderFormDialog.vue'
import HealthInfoDialog from './components/HealthInfoDialog.vue'
import CheckTaskDialog from './components/CheckTaskDialog.vue'
import {CheckType} from "@/types/checkType";

const loading = ref(false)
const elderList = ref<Elder[]>([])
const communityList = ref<Community[]>([])


// 对话框相关
const healthDialog = ref(false)
const taskDialog = ref(false)
const elderFormVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentElder = ref<Elder>()
// 其他变量不变
const communityLoading = ref(false)
const filteredCommunityList = ref<Community[]>([])

const searchParams = ref({
  elderName: '',
  phone: '',
  communityId: null
})

async function getData(){
  try {
    loading.value = true
    await fetchCommunityList() // 先获取社区列表
    await Promise.all([
      fetchElderList(),
    ])
  } catch (error) {
    console.error('初始化失败:', error)
  } finally {
    loading.value = false
  }
}

onActivated(() => {
  getData()
})

// 获取老人列表
const fetchElderList = async () => {
  try {
    const elders = await getAllElders({
      elderName: searchParams.value.elderName,
      phone: searchParams.value.phone,
      communityId: searchParams.value.communityId
    })
    // 获取所有老人的检查任务
    const elderPromises = elders.map(async (elder) => {
      try {
        const tasks = await getElderCheckTasks({elderId: elder.id, date: null})
        return {
          ...elder,
          healthInfo: elder.healthInfo || {
            medical_history: '',
            medication_records: ''
          },
          communityName: communityList.value.find(c => c.id === elder.communityId)?.name || '',
          checkTasks: tasks || []
        }
      } catch (error) {
        console.error(`获取老人 ${elder.id} 的检查任务失败:`, error)
        return {
          ...elder,
          healthInfo: elder.healthInfo || {
            medical_history: '',
            medication_records: ''
          },
          communityName: communityList.value.find(c => c.id === elder.communityId)?.name || '',
          checkTasks: []
        }
      }
    })

    // 等待所有老人的检查任务获取完成
    elderList.value = await Promise.all(elderPromises)
  } catch (error) {
    console.error('获取老人列表失败:', error)
  }
}


// 搜索方法
const handleSearch = () => {
  fetchElderList();
}

// 重置搜索
const resetSearch = () => {
  searchParams.value = {
    elderName: '',
    phone: '',
    communityId: null
  };
  fetchElderList();
}

// 社区过滤方法
const filterCommunity = (query: string) => {
  if (query) {
    communityLoading.value = true
    setTimeout(() => {
      filteredCommunityList.value = communityList.value.filter(item => {
        return item.name.includes(query)
      })
      communityLoading.value = false
    }, 200)
  } else {
    filteredCommunityList.value = communityList.value
  }
}

// 修改 fetchCommunityList 方法
const fetchCommunityList = async () => {
  try {
    communityList.value = await getAllCommunities()
    filteredCommunityList.value = communityList.value
  } catch (error) {
    console.error('获取社区列表失败:', error)
  }
}


// 添加老人
const handleAdd = async () => {
  try {
    dialogType.value = 'add'
    currentElder.value = undefined

    // 确保社区列表已加载
    if (communityList.value.length === 0) {
      await fetchCommunityList()
    }

    elderFormVisible.value = true
  } catch (error) {
    console.error('准备添加数据失败:', error)
  }
}

// 编辑老人
const handleEdit = async (row: Elder) => {
  try {
    dialogType.value = 'edit'
    currentElder.value = row

    // 确保社区列表已加载
    if (communityList.value.length === 0) {
      await fetchCommunityList()
    }

    // 确保老人列表已加载
    if (elderList.value.length === 0) {
      await fetchElderList()
    }

    elderFormVisible.value = true
  } catch (error) {
    console.error('准备编辑数据失败:', error)
  }
}

// 删除老人
const handleDelete = async (row: Elder) => {
  try {
    await ElMessageBox.confirm(
        '删除后将无法恢复该老人的所有信息，包括健康信息和检查任务以及老人和子女的绑定信息，是否确认删除？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          draggable: true,
          closeOnClickModal: false
        }
    )
    await deleteElder(row.id)
    ElMessage.success('删除成功')
    await fetchElderList()
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    }
  }
}

// 表单提交成功回调
const handleSuccess = () => {
  fetchElderList()
}

// 查看健康信息
const handleViewHealth = (row: Elder) => {
  currentElder.value = row
  healthDialog.value = true
}

// 检查任务相关
const handleCheckTasks = async (row: Elder) => {
  currentElder.value = row
  try {
    taskDialog.value = true
  } catch (error) {
    console.error('准备检查任务数据失败:', error)
  }
}

// 获取健康状态
const getHealthStatusType = (elder: Elder) => {
  if (!elder.checkTasks?.length) return 'info'
  const hasUnfinishedTasks = elder.checkTasks.some(task => !task.finish)
  const hasQuestions = elder.checkTasks.some(task => task.hasQuestion)
  if (hasQuestions) return 'danger'
  if (hasUnfinishedTasks) return 'warning'
  return 'success'
}

const getHealthStatusText = (elder: Elder) => {
  if (!elder.checkTasks?.length) return '未检查'
  const hasUnfinishedTasks = elder.checkTasks.some(task => !task.finish)
  const hasQuestions = elder.checkTasks.some(task => task.hasQuestion)
  if (hasQuestions) return '异常'
  if (hasUnfinishedTasks) return '待检查'
  return '正常'
}
</script>

<style scoped>

.fixed-header {
  flex-shrink: 0;
  padding-bottom: 20px;
  background-color: #fff;
  z-index: 1;
}

.elder-list-container {
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 95%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #303133;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 10px; /* 统一设置元素间间距 */
}

/* 统一输入框和按钮的宽度和间距 */
.search-group .el-input,
.search-group .el-select,
.search-group .el-button {
  margin: 0; /* 清除默认margin */
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button) {
  transition: all 0.3s;
}

:deep(.el-button.is-link) {
  height: 32px;
  padding: 0 12px;
  font-size: 14px;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-button.is-link.el-button--danger:hover) {
  background-color: #fef0f0;
}

:deep(.el-button.is-link.el-button--primary:hover) {
  background-color: #ecf5ff;
}

:deep(.el-button.is-link.el-button--success:hover) {
  background-color: #f0f9eb;
}

:deep(.el-button.is-link.el-button--info:hover) {
  background-color: #f4f4f5;
}

:deep(.el-avatar) {
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 添加表格行悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

/* 添加表格边框和圆角 */
:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table__fixed-right) {
  background-color: #fff;
}

:deep(.el-table__fixed-right::before) {
  background-color: #f5f7fa;
}

:deep(.el-table__fixed-right-patch) {
  background-color: #f5f7fa;
}

/* 添加对话框标题样式 */
:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

/* 添加对话框内容区域样式 */
:deep(.el-dialog__body) {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

/* 添加按钮样式 */
.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
  transition: all 0.3s;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
  transition: all 0.3s;
}

.el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
  color: #fff;
  transition: all 0.3s;
}

.el-button--success:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

.el-button--info {
  background-color: #909399;
  border-color: #909399;
  color: #fff;
  transition: all 0.3s;
}

.el-button--info:hover {
  background-color: #a6a9ad;
  border-color: #a6a9ad;
}

.elder-form {
  padding: 20px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  margin: 0 auto;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  margin: 0 auto;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.task-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: normal;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-switch) {
  margin-top: 4px;
}
</style> 